﻿var express = require('express');
var router = express.Router();
var log = require('../util/logger.js');
var db = require('../db/db.js');
var crypto = require("crypto");
var config = require('../config.js');
var moment = require("moment");
var myutil = require('../util/util.js');
var wx = require('../util/wx');


router.post('/wxcallback', async function (req, res) {

    var result = req.body;
    log.info("微信支付回调" + JSON.stringify(result));
    if (result.xml.result_code == 'SUCCESS' && result.xml.return_code == 'SUCCESS') {


        var orderinfo = await db.query("select * from orders  where ordernum=?", [result.xml.out_trade_no]);
        //and pay_status=0
        if (orderinfo.length > 0) {

            if (orderinfo[0].pay_status == 0) {
                var sql = "update orders set pay_status=1,pay_time=?,transaction_id=? where ordernum=?";
                var obj = await db.execute(sql, [new Date(), result.xml.transaction_id, result.xml.out_trade_no]);
                //    console.log("code" + obj.code);
                if (obj.code == 200) {


                    if (orderinfo[0].mid != "0") {

                        db.asynquery("update merchant set money=money+" + orderinfo[0].total_fee + " where id=" + orderinfo[0].mid, [],
                            function (err, info) {
                                log.info("给商户加钱结果" + err + JSON.stringify(info));
                            });
                    }


                    res.write("success");
                    res.end();


                } else {
                    log.info("支付失败，更新订单失败,订单号:" + result.xml.out_trade_no);
                    res.write("error");
                    res.end();
                }
            } else if (orderinfo[0].pay_status == 1) {
                log.info("订单已支付:" + result.xml.out_trade_no);
                res.write("success");
                res.end();
            } else {
                log.info("订单状态不是0也不是1:" + result.xml.out_trade_no);
                res.write("error");
                res.end();

            }

        } else {
            log.info("不存在的订单:" + result.xml.out_trade_no);
            res.write("error");
            res.end();
        }


    } else {
        log.info("支付失败,订单号：" + result.xml.out_trade_no + ",错误码:" + result.xml.result_code);
        res.write("error");
        res.end();
    }



})
module.exports = router;   /*暴露这个 router模块*/